/*
 * @Author: shijianxin
 * @Date: 2022-04-21 15:24:07
 * @Description: 基础类
 */

import { ClassConstructor, plainToClass } from "class-transformer";
import { validate } from "class-validator";

export abstract class BaseEntity {
  /**
   * 验证当前电影对象
   */
  public async validateThis(skipMissing = false): Promise<string[]> {
    const errors = await validate(this, {
      skipMissingProperties: skipMissing,
    });
    const result: string[] = [];
    errors.forEach((e) => {
      for (let i in e.constraints) {
        result.push(e.constraints[i]);
      }
    });
    return result;
  }

  /**
   * 将一个平面对象转换为Movie类对象
   * @param plainObject
   * @returns
   */
  protected static baseTransform<T>(
    cls: ClassConstructor<T>,
    plainObject: object
  ): T {
    if (plainObject instanceof cls) {
      return plainObject;
    }
    return plainToClass(cls, plainObject);
  }
}
